/**
 * axios全局配置
 */
import Qs from 'qs';
import {
  Message
} from 'element-ui';
import VueCookies from 'vue-cookies'
import { apiAddress } from '~/util/config.js'


export default function (app) {
  let axios = app.$axios;
  // 基本配置
  //axios.defaults.timeout = 10000;

  if (process.env.NODE_ENV == 'production') {//如果是生产环境
    // axios.defaults.baseURL = 'http://192.168.124.110' //线上
    axios.defaults.baseURL = apiAddress //线上
  } else {
    // axios.defaults.baseURL = '' //本地
    // axios.defaults.baseURL = 'http://192.168.124.66' //本地
    axios.defaults.baseURL = apiAddress //线上
  }

  axios.defaults.headers.common['Authorization'] = "Bearer " + app.store.state.token;
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


  //参数序列化
  axios.interceptors.request.use((config) => {
    if (config.method == 'get') {
      if (config.params) {
        let params = {}
        for (let i in config.params) {
          if (config.params[i]) {
            params[i] = config.params[i]
          }
        }
        config.params = params
      }
    }
    if (config.method === 'post') {
      config.data = Qs.stringify(config.data)
    }
    return config;
  }, (error) => {
    return Promise.reject(error)
  })
  //响应拦截器
  axios.interceptors.response.use(
    response => {
      if (response.data.code == 401) {
        /*
         * 如果请求报错是因为token不存在或过期，就重新登录
         */
        Message({
          message: app.store.state.token ? "您需要重新登录" : "您还没有登录",
          type: "warning"
        });
        app.store.commit('delToken');
        VueCookies.remove('token');
        // app.redirect('/admin/login');

        let toPath = getToPath(app)
        app.redirect(toPath);
      }
      return response;
    },
    error => {
      return Promise.resolve(error)
    });
}


// 处理要跳转到那个页面
function getToPath(app) {
  let fullPath = app.route.fullPath
  let path = app.route.path
  let query = app.route.query
  let agent = '/agent'
  let redirectURL = '/'
  let user = '/user'
  // 如果是公共支付页面
  if (path == "/payment") {
    // 如果有from参数
    if (query.from) {
      if(query.from.search(user) != -1) {
        return `${redirectURL}login?type=2&routerfrom=${escape(fullPath)}`
      } else if (query.from.search(agent) != -1) {
        return `${redirectURL}login?type=1&routerfrom=${escape(fullPath)}`
      } else {
        return redirectURL
      }
    } else {
      return redirectURL
    }
  } else {
    if(path.search(user) != -1) {
      return `${redirectURL}login?type=2&routerfrom=${escape(fullPath)}`
    } else if (path.search(agent) != -1) {
      return `${redirectURL}login?type=1&routerfrom=${escape(fullPath)}`
    } else {
      return redirectURL
    }
  }
}